﻿using FarseerGames.FarseerPhysics.Mathematics;
using FreeGoo.GameEngine.Renderables.Particles;

namespace FreeGoo.GameEngine
{
    public class UserInputController
    {
        internal UserInputController(Engine engine)
        {
            Engine = engine;
        }

        public Engine Engine { get; private set; }
        public Vector2 CursorPosition { get; set; }
        public bool IsMouseDown { get; set; }
        public Particle SelectedParticle { get; set; }        

        public void MouseDown(Vector2 cursorPosition)
        {
            if (IsMouseDown)
            {
                MouseMoveCancelledUp();
            }

            CursorPosition = cursorPosition;

            SelectedParticle = Engine.GetParticleForPosition(CursorPosition, true);

            if (SelectedParticle != null && SelectedParticle.CanBeSelected)
            {
                IsMouseDown = true;
                SelectedParticle.Selected(CursorPosition);
            }
        }                

        public void MouseUp()
        {
            Release(false);
        }
        
        public void MouseUp(Vector2 cursorPosition)
        {
            CursorPosition = cursorPosition;
            MouseUp();
        }

        public void MouseMoveCancelledUp()
        {
            Release(true);
        }

        public void MouseMove(Vector2 cursorPosition)
        {
            CursorPosition = cursorPosition;
            if (IsMouseDown)
            {
                SelectedParticle.ControllerMovedTo(cursorPosition);                
            }
        }
        
        internal void Release(bool canceled)
        {
            if (IsMouseDown)
            {
                IsMouseDown = false;

                if (!canceled && !SelectedParticle.IsLinked)
                {
                    SelectedParticle.Placed();
                }
                else
                {
                    SelectedParticle.DeSelected();
                }
            }
        }
    }
}
